package com.cloudbroker.bcs.platform.dav.middle.aspect;

import com.cloudbroker.bcs.common.entity.Markable;
import com.cloudbroker.bcs.common.mycat.route.function.PartitionByMurmurHash;
import com.cloudbroker.bcs.platform.dav.common.config.ConfigValues;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.lang.reflect.Method;

/**
 * Created by xuyn15828 on 2016/6/7.
 */
public class MycatLogAspect {
    private static final Logger logger = LoggerFactory.getLogger(MycatLogAspect.class);
    public static final String OPERATION_SAVE = "save";

    public Object log(ProceedingJoinPoint pjp) throws Throwable {
        Method method = ((MethodSignature)pjp.getSignature()).getMethod();
        if( method.getName().equals(OPERATION_SAVE) && ConfigValues.getMycatFlag() ) {
            logSave(pjp);
        }
        return pjp.proceed();
    }

    private void logSave(ProceedingJoinPoint pjp) {
        Object[] objAry = pjp.getArgs();
        if( null != objAry && 0 != objAry.length ) {
            for(Object obj : objAry) {
                if( obj instanceof Markable ) {
                    Markable markable = (Markable) obj;
                    Integer tenantId = markable.getTenant_id();
                    logger.debug("the " + obj + " will save in " +
                            PartitionByMurmurHash.caluateMurmurHash(ConfigValues.getMycatNum() , tenantId+"") + ".th bucket" );
                }
            }
        }
    }
}
